package com.thenie.seckill.interceptor;

import com.thenie.seckill.pojo.User;
import com.thenie.seckill.service.IUserService;
import com.thenie.seckill.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登陆拦截器
 */

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtil.getCookieValue(request, "userTicket");

        //已经登陆过，放行
        if (!StringUtils.isEmpty(ticket)){
            User user = userService.getUserByCookie(ticket, request, response);

            if (user!=null){
                request.setAttribute("currentUser",user);
                return true;
            }
        }

        //跳转登陆页面
        request.getRequestDispatcher("/login/toLogin").forward(request,response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
